package com.wwinsoft.framework.web.security;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Lists;
import com.wwinsoft.framework.entity.security.Group;
import com.wwinsoft.framework.entity.security.User;
import com.wwinsoft.framework.pojo.common.MenuTree;
import com.wwinsoft.framework.service.ServiceException;
import com.wwinsoft.framework.service.security.AccountManager;
import com.wwinsoft.framework.service.system.CodeManager;
import com.wwinsoft.framework.utils.JXLTHelper;
import com.wwinsoft.framework.utils.MenuUtils;
import com.wwinsoft.framework.web.CrudActionSupport;
import com.wwinsoft.modules.orm.Page;
import com.wwinsoft.modules.orm.PropertyFilter;
import com.wwinsoft.modules.security.springsecurity.SpringSecurityUtils;
import com.wwinsoft.modules.utils.encode.JsonBinder;
import com.wwinsoft.modules.utils.reflection.ConvertUtils;
import com.wwinsoft.modules.utils.web.struts2.Struts2Utils;

/**
 * 用户管理Action.
 * <p/>
 * 使用Struts2 convention-plugin annotation定义Action参数. 演示带分页的管理界面.
 *
 * @author calvin
 */
//定义URL映射对应/security/user.action
@Namespace("/security")
//定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results({ @Result(name = CrudActionSupport.RELOAD, location = "user.action", type = "redirect"),
                 @Result(name = "profileReload", location = "user!profile.action", type = "redirect")})
public class UserAction extends CrudActionSupport<User> {

    private static final long serialVersionUID = 8683878162525847072L;

    private static final String USER_EXCEL_TEMPLATE = "/template/excel/User_Template.xls";

    @Autowired
    private AccountManager accountManager;

 // add by sevenSpend 2011/11/27 -->
    private JsonBinder jsonBinder = JsonBinder.buildNormalBinder();
// <-- add by sevenSpend 2011/11/27

    //-- 页面属性 --//
    private Long id;
    private User entity;
    private Page<User> page = new Page<User>();
    private List<Long> checkedRoleIds = Lists.newArrayList();
    private List<Long> checkedDeptIds = Lists.newArrayList();
 // add by sevenSpend 2011/11/27 -->
    private String checkedDeptIdsStr;//页面中勾选的部门id拼接出来的字符串  
 // <-- add by sevenSpend 2011/11/27

    //-- ModelDriven 与 Preparable函数 --//


    public void setId(Long id) {
        this.id = id;
    }

    public User getModel() {
        return entity;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id!=null) {
            entity = accountManager.getUser(id);
        } else {
            entity = new User();
        }
    }

    //-- CRUD Action 函数 --//
    @Override
    public String list() throws Exception {
        List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
        //设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.ASC);
        }
        page = accountManager.searchUser(page, filters);

        // <-- add by sevenSpend 2011-11-28 end
        
        return SUCCESS;
    }
    
    public void listExp() throws Exception{
        List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
        //设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.ASC);
        }
        List<User> userList = accountManager.searchUser(filters);
        exportExcel(userList);
    }

    private void exportExcel(List<User> userList) {
        Map<String, Object> beans = new HashMap<String, Object>();
        beans.put("dataList", userList);
        beans.put("accountManager", accountManager);

        String fileName = "用户列表";
        JXLTHelper.writeXLTtoResponse(beans, USER_EXCEL_TEMPLATE, fileName);
    }

    @Override
    public String input() throws Exception {
        checkedRoleIds = entity.getRoleIds();
        checkedDeptIds = entity.getUiGroupIds();
        return INPUT;
    }

    @Override
    public String save() throws Exception {
        checkedDeptIds =  ConvertUtils.convertSeparatorStringToList(checkedDeptIdsStr, ",", Long.class);
        accountManager.saveUser(entity, checkedRoleIds,checkedDeptIds);

        addActionMessage("保存用户成功");
        return RELOAD;
    }

    public void prepareProfile() throws Exception{
        String currentUserName = SpringSecurityUtils.getCurrentUserName();
        entity = accountManager.findUserByLoginName(currentUserName);
    }

    public String profile() throws Exception{
        return "profile";
    }

    public void prepareSaveProfile() throws Exception{
        prepareModel();
    }

    public String saveProfile() throws Exception {
        accountManager.saveUser(entity);
        addActionMessage("保存个人信息成功");
        return "profileReload";
    }

    @Override
    public String delete() throws Exception {
        try {
            accountManager.deleteUser(id);
            addActionMessage("删除用户成功");
        } catch (ServiceException e) {
            logger.error(e.getMessage(), e);
            addErrorMessage(e.getMessage());
        }
        return RELOAD;
    }

    //-- 其他Action函数 --//

    /**
     * 支持使用Jquery.validate Ajax检验用户名是否重复.
     */
    public String checkLoginName() {
        HttpServletRequest request = ServletActionContext.getRequest();
        String newLoginName = request.getParameter("userId");
        String oldLoginName = request.getParameter("oldUserId");

        if (accountManager.isLoginNameUnique(newLoginName, oldLoginName)) {
            Struts2Utils.renderText("true");
        } else {
            Struts2Utils.renderText("false");
        }
        //因为直接输出内容而不经过jsp,因此返回null.
        return null;
    }

    public String getCurrentUserByAjax() {
        User user = accountManager.findUserByLoginName(SpringSecurityUtils.getCurrentUserName());
        Struts2Utils.renderJson(user);
        return null;
    }

    // add by sevenSpend 2011/11/27 -->
       public String getDeptJson(){
           List<Group> allDept = accountManager.getAllDept();
           MenuTree menuTree = MenuUtils.buildMenuTreeWithRoot(allDept, "所有部门");
           return jsonBinder.toJson(menuTree);
       }
    // add by sevenSpend 2011/11/27 <--



    //-- 页面属性访问函数 --//

    /**
     * list页面显示用户分页列表.
     */
    public Page<User> getPage() {
        return page;
    }

    /**
     * input页面显示所有角色列表.
     */
    public List<Group> getAllRoleList() {
        return accountManager.getAllRole();
    }

    /**
     * input页面显示所有部门列表.
     */
    public List<Group> getAllDeptList() {
        return accountManager.getAllDept();
    }

    public List<Long> getCheckedRoleIds() {
        return checkedRoleIds;
    }

    public void setCheckedRoleIds(List<Long> checkedRoleIds) {
        this.checkedRoleIds = checkedRoleIds;
    }

    public List<Long> getCheckedDeptIds() {
        return checkedDeptIds;
    }

    public void setCheckedDeptIds(List<Long> checkedDeptIds) {
        this.checkedDeptIds = checkedDeptIds;
    }

   public String getCheckedDeptIdsStr() {
   		return StringUtils.join(checkedDeptIds,",");
   	}

   	public void setCheckedDeptIdsStr(String checkedDeptIdsStr) {
   		this.checkedDeptIdsStr = checkedDeptIdsStr;
   	}

}
